<template>
  <view class="u-select-plus" :class="disabled && 'u-select-plus-disabled'">
    <view class="u-select-plus-editor"
          :style="{'border-color': Boolean(msg) ? '#DCDCDC' : '#EBEEF5'}" @tap="handleShow">
      <u-input class="input" v-model="temp" :placeholder="placeholder" />
      <u-icon v-if="!temp" name="search" color="#c0c4cc" size="45" />
      <view @tap.stop="handleClear">
        <u-icon v-if="temp && clearable && !disabled" name="close-circle-fill" color="#c0c4cc" size="45" />
      </view>
    </view>
    <u-popup :show="visible">
      <view class="u-select-plus-popup">
          <view class="popup-header u-p-r-20 u-p-l-20 u-p-b-15">
          <view class="popup-search u-m-r-20 u-p-l-10 u-p-r-10">
            <u-icon name="search" color="#c0c4cc" size="44"/>
            <input
                class="popup-search-input u-p-l-10 u-p-r-10"
                type="text"
                v-model="keyword"
                confirm-type="search"
                @input="handleInput"
                @blur="handleBlur"
                ref="inputField"
            />
<!--            <u-icon name="close-circle-fill" color="#c0c4cc" size="44" @click="handleClear"/>-->
          </view>
          <!--          <view class="popup-btn" style="margin-left: -10rpx">-->
          <!--            <u-button type="success" :style="{height:'74rpx'}" @click="handleInput">搜索</u-button>-->
          <!--          </view>-->
          <view class="popup-btn" style="border: #d2d2d2 2rpx solid">
            <u-button type="primary" :style="{height:'70rpx'}" @click="handleClose">关闭
            </u-button>
          </view>
        </view>
        <scroll-view class="scroll-box"
                     :style="{marginTop: '110rpx'}"
                     scroll-y="true"
                     :refresher-enabled="isRefresher"
                     lower-threshold="10"
                     :refresher-triggered="trigger"
                     @refresherpulling="refresherpullingFun"
                     @refresherrefresh="refresherrefreshFun"
                     @scrolltolower="scrolltolowerFun">
          <view v-if="!keyword" style="height: 100% !important;">
            <template v-if="tableList.length > 0">
              <view class="scroll-item u-flex u-row-between u-p-l-20 u-p-r-20"
                    @tap="handleSelect(item)"
                    v-for="(item, index) in tableList" :key="index">
                <view v-if="defaultItemLayout === true">
                  <text class="u-line-1 u-font-md u-text-normal"
                        v-for="(val, idx) in showColumn"
                        :key="idx"
                  >{{ showItem(item,val) }}</text>
                </view>
                <slot v-else :item="item" :index="index" name="item"/>
              </view>
            </template>
            <view style="height: 80% !important;align-items: center; justify-content: center" class="u-flex" v-else>
              <u-empty mode="data" :icon="icon" text="--暂无数据--" textSize="28"/>
            </view>
          </view>
          <view v-if="keyword" style="height: 100% !important;">
            <template v-if="tableList.length > 0">
              <view class="scroll-item u-flex u-row-between u-p-l-20 u-p-r-20"
                    @tap="handleSelect(item)"
                    v-for="(item, index) in gridData" :key="index">
                <view v-if="defaultItemLayout === true">
                  <text class="u-line-1 u-font-md u-text-normal"
                        v-for="(val, idx) in showColumn"
                        :key="idx"
                  >{{ showItem(item,val) }}</text>
                </view>
                <slot v-else :item="item" :index="index" name="item"/>
              </view>
            </template>
            <view style="height: 80% !important;align-items: center; justify-content: center" class="u-flex" v-else>
              <u-empty mode="data" :icon="icon" text="--暂无数据--" textSize="28"/>
            </view>
          </view>
        </scroll-view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import props from './props';
import mpMixin from '../../../mixin/mpMixin';
import icon from '../../../static/mld/data.png'
export default {
  name: 'u-select-plus',
  mixins: [mpMixin, props],
  emits: ['select', 'update:modelValue', 'update:inputInner', 'input', 'clear', 'change'],
  model: {
    prop: 'modelValue',
    event: 'update:modelValue'
  },
  options: {
    virtualHost: true
  },
  inject: {
    form: {
      from: 'uniForm',
      default: null
    },
    formItem: {
      from: 'uniFormItem',
      default: null
    }
  },
  data() {
    return {
      deviceModel:'',
      icon,
      temp: '',
      fixLabel: '',
      localMsg: '',
      visible: false,
      queryParam: {
        pageNum: 1,
        pageSize: this.defaultPageSize
      },
      gridData: [],
      fitterGridData: [],
      filterGridData: [],
      tableList: [],
      currentPage: 1,
      total: 0,
      keyword: '', //搜索关键字
      isRefresher: true,  // 开启自定义下拉刷新
      trigger: false, //当前下拉刷新状态
      prevKeyword: '', // 新增：用于保存上一次的关键词
      platform:'' // 当前机型
    }
  },
  onShow() {},
  computed: {
    msg() {
      return this.localMsg || this.errorMessage;
    }
  },
  watch: {
    inputInner(val) {
      if (val) {
        this.temp = val;
        this.fixLabel = val;
      } else {
        this.temp = '';
        this.fixLabel = '';
      }
    },
    value(val) {
      if (!val) {
        this.clear()
      }
    },
    visible(val) {
      if (!val) {
        this.keyword = '';
        this.filterGridData = [];
      }
    },
    filterGridData(val) {
      // console.log('filterGridData', val)
    }
  },
  created() {
    uni.getSystemInfo({
      success: (res) => {
        this.platform = res.osName;
      }
    });
    if (this.form && this.formItem) {
      this.$watch('formItem.errMsg', newVal => {
        this.localMsg = newVal;
      });
    }
  },
  mounted() {
    this.getDeviceModel();
    if (this.inputInner) {
      this.temp = this.inputInner;
      this.fixLabel = this.temp;
    }
  },
  methods: {
    // 获取手机型号
    getDeviceModel() {
      uni.getSystemInfo({
        success: (res) => {
          this.deviceModel = res.model;
          // console.log('手机型号:', this.deviceModel);
        },
        fail: (err) => {
          console.error('获取系统信息失败:', err);
        }
      });
    },
    init() {
      let param = this.queryParam;
      if (this.filterKey) {
        this.queryParam[this.filterKey] = this.keyword;
      }
      if (this.defaultQueryParam) {
        param = Object.assign(this.queryParam, this.defaultQueryParam);
      }
      this.getGridData(param);
    },
    getGridData(param) {
      if (this.paramLimit > this.temp.length) {
        this.filterGridData = [];
        return;
      }

      this.loading = true;
      this.interface(param).then(res => {
        this.loading = false;
        if (this.filterKey) {
          delete this.queryParam[this.filterKey];
        }
        let {success, data, message} = res.data;
        if (success) {
          if (data.list) {
            this.gridData = data.list;
            this.total = data.total;
          }
          if (data instanceof Array) {
            this.total = -1;
            this.gridData = data;
          }
          // this.queryParam.pageNum++;
          this.filterGridData = [...this.filterGridData, ...this.gridData]
          this.tableList = this.filterGridData;
        } else {
          uni.showToast({
            title: '获取数据失败'+message,
            icon: 'error',
            duration: 3000
          })
        }
      }).catch(() => {
        this.loading = false;
        uni.showToast({
          title: '获取数据失败',
          icon: 'error',
          duration: 3000
        })
      }).finally(() => {
        this.loading = false;
        this.trigger = false;
      })
    },
    handleInput() {
      const val = this.keyword;
      console.log('input' + val)
      if (this.allowCustom) {
        this.$emit('input', val);
        this.$emit('update:modelValue', val);
        this.$emit('select', val);
        this.$emit('update:inputInner', val);
        this.$emit('change', val);
      }
      if (!val) {
        this.filterGridData = [];
        this.tableList = [];
        if (this.defaultQuery) {
          this.clear();
          if (this.total > 0) {
            if (this.filterKey) {
              this.queryParam[this.filterKey] = val;
            }
            this.queryParam.pageNum = 1;
            this.queryParam.pageSize = this.defaultPageSize;
            this.getGridData(this.queryParam);
            return;
          }
        } else {
          this.filterGridData = [];
          this.gridData = [];
        }
        return;
      }
      if (val !== this.prevKeyword) {
        this.prevKeyword = val;
        if (this.total >= 0) {
          this.queryParam.pageNum = 1;
          this.queryParam.pageSize = this.defaultPageSize;
          if (this.keyword) {
            if (this.autoUpperCase) {
              this.queryParam[this.filterKey] = val.toUpperCase();
            } else {
              this.queryParam[this.filterKey] = val;
            }
          }
          this.getGridData(this.queryParam);
        } else {
          this.tableList = this.gridData.filter(data => {
            let bool = false;
            for (let i = 0; i < this.showColumn.length; i++) {
              const col = this.showColumn[i];
              const prop = col.prop;
              if (data[prop] && data[prop].indexOf(val) > -1) {
                bool = true;
              }
            }
            return bool;
          });
        }
      }
    },
    handleShow() {
      if (this.disabled) {
        return
      }
      this.queryParam.pageNum = 1;
      this.init();
      this.visible = true;
      this.handleBlur();
    },
    // 滚动到底部/右边
    scrolltolowerFun() {
      if (this.queryParam.pageNum * this.queryParam.pageSize >= this.total) {
        uni.showToast({
          title: '数据加载完毕',
          icon: 'none',
          duration: 1000
        });
        setTimeout(() => {
          uni.hideLoading()
        }, 500)
      } else {
        if (this.keyword) {
          this.queryParam[this.filterKey] = this.keyword;
        }
        const param = Object.assign(this.queryParam,{
          pageNum: ++this.queryParam.pageNum
        })
        console.log('----滚动到底部--this.queryParam.pageNum--' + this.queryParam.pageNum)
        this.getGridData(param);
      }
    },
    // 自定义下拉刷新控件被下拉
    async refresherpullingFun() {
      console.log('下拉刷新了')
      setTimeout(() => {
        this.trigger = false;
      }, 1500)
    },
    async refresherrefreshFun() {
      console.log('滚动到顶部了');
      this.trigger = true
      this.queryParam.pageNum = 1;
      this.filterGridData = [];
      if (this.keyword) {
        this.queryParam[this.filterKey] = this.keyword;
      }
      await this.getGridData(this.queryParam);
    },
    handleBlur() {
      if (!this.allowCustom && !this.filterKey) {
        this.clear();
        this.visible = false;
      }
    },
    handleClose() {
      // this.clear();
      // this.currentPage = 1;
      this.temp = this.keyword;
      this.visible = false;
      // this.$emit('clear', null);
    },
    handleClear() {
      if (this.disabled) {
        return
      }
      this.currentPage = 1;
      this.temp = '';
      this.clear();
      this.$emit('clear', null);
    },
    clear() {
      this.temp = '';
      console.log('input', '')
      this.$emit('input', '');
      this.$emit('update:modelValue', '');
      this.$emit('select', null);
      this.$emit('update:inputInner', '');
      this.$emit('change', null);
    },
    handleSelect(row) {
      console.log('handleSelect', row)
      this.temp = row[this.inputLabel];
      this.fixLabel = this.temp;
      console.log('input', row[this.inputKey])
      this.$emit('input', row[this.inputKey]);
      this.$emit('update:modelValue', row[this.inputKey]);
      this.$emit('select', row);
      this.$emit('update:inputInner', this.temp);
      this.$emit('change', row[this.inputKey]);
      this.visible = false;
    },
    //显示条目
    showItem(item,val) {
      if (this.showItemLabel) {
        return val.label + "：" + (item[val.prop] ? item[val.prop].replace(/^,/, '') : '');
      } else {
        return item[val.prop]?item[val.prop].replace(/^,/, '') : '';
      }

    },
    //处理返回按钮按下事件
    handleBackPress(){
      if (this.visible) {
        this.visible = false;
        return true;
      } else {
        return false;
      }

    }
  }
}
</script>

<style lang="scss" scoped>

.u-select-plus {
  /* #ifndef APP-NVUE */
  width: 100%;
  /* #endif */
  flex: 1;
  position: relative;
  text-align: left;
  color: #333;
  font-size: 14px;
  border-radius: 5px;

  &-editor {
    font-size: 14px;
    box-sizing: border-box;
    border-radius: 4px;
    padding: 0 5px;
    position: relative;
    display: flex;
    user-select: none;
    flex-direction: row;
    align-items: center;
    border: 1px solid #DCDCDC;

    .u-select-plus-input {
      font-size: 12px;
      min-height: 35px;
      position: relative;
      /* #ifndef APP-NVUE */
      display: flex;
      /* #endif */
      flex: 1;
      flex-direction: row;
      align-items: center;
    }
  }

  &-popup {
    height: 100vh;

    .popup-header {
      display: flex;
      flex: 1;
      flex-direction: row;
      align-items: center;
      padding: 6px 10px 10px 10px;
      border-bottom: solid 1px #DCDCDC;
      position: absolute;
      left: 0;
      right: 0;

      .popup-search {
        /* #ifndef APP-NVUE */
        display: flex;
        /* #endif */
        flex: 1;
        flex-direction: row;
        align-items: center;
        border-radius: rpx(8);
        border: solid 1px #DCDCDC;

        .popup-search-input {
          height: 35px;
          position: relative;
          /* #ifndef APP-NVUE */
          display: flex;
          /* #endif */
          flex: 1;
          flex-direction: row;
          align-items: center;
        }
      }
    }

    .scroll-title {
      height: 42px;
      width: 100%;
      color: #000000;
      font-weight: bold;
      border-top: 1px solid #DCDCDC;
      background: #f5f7fa;
      -webkit-box-shadow: 0 2px 2px 0 rgba(62, 66, 66, 0.3);
      -moz-box-shadow: 0 2px 2px 0 rgba(62, 66, 66, 0.3);
      box-shadow: 0 2px 2px 0 rgba(62, 66, 66, 0.3);

      text {
        flex: 1;
        flex-shrink: 0;
        text-align: center;
      }

      .scroll-title_placeholder {
        width: 22px;
      }
    }

    .scroll-box {
      height: calc(100% - 60px);
      overflow-y: scroll;

      .scroll-item:active {
        background-color: lightgray;
      }

      .scroll-item {
        display: flex;
        flex-direction: column;
        align-items: start;
        line-height: 40px;
        border-bottom: 1px solid #DCDCDC;

        text {
          flex: 1;
          flex-shrink: 0;
          text-align: left;
        }
      }
    }
  }

  &-disabled {
    background-color: #f7f6f6;
    color: #d5d5d5;
    border-color: rgb(229, 229, 229);
  }

  .input {
    pointer-events: none;
  }
}
::v-deep uni-scroll-view-refresher .uni-scroll-view-refresh-inner {
  height: 0 !important;
  width: 0 !important;
}
</style>